﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using TpsAutoSurvey_PDA_Version_.Presenter;
using TpsAutoSurvey_PDA_Version_.Model;
using System.Threading;
using TpsAutoSurvey_PDA_Version_.SocketModule;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

namespace TpsAutoSurvey_PDA_Version_.RealizedClasses
{
    public class SurveyDistController:SurveyBase
    {
        DistantMeasureCom geo;
        public override event EventHandler OnerrHappen;
        public override event EventHandler OnSurveyComplete;

        private List<svpoint> tempConfigPoints = new List<svpoint>();//当前的待测数据集

        private List<svpoint> configPoints = new List<svpoint>();//所有的数据集



      
        public SurveyDistController()
            : base()
        {
            //base.OnerrHappen += new EventHandler(OnerrHappen);
            //base.OnSurveyComplete += new EventHandler(OnSurveyComplete);
        }

        public override CommandPara PrepareStation(CommandPara p)
        {
            try
            {
                IsWorking = false;
                if (geo != null && geo.port.IsOpen == true)
                {
                    geo.port.Close();
                }
                this.datatrans = new DataTransmission();
                this.configPoints = datatrans.GetConfigPoints();
                geo = this.datatrans.distCom;
            }
            catch (Exception a)
            {
                ToolClass.Log(a.Message);
                p.result = "重置失败," + a.Message;
                return p;
            }
            return base.PrepareStation(p);
        }


        private void Survey()
        {
            ToolClass.Log(string.Format("Survey!!"));
            try
            {
                if (geo == null || geo.port == null || geo.port.IsOpen == false)
                {
                    para = para == null ? new CommandPara("","") : para;
                    para.result = "没有打开串口!";
                    if (OnerrHappen != null)
                    {
                        OnerrHappen(para, new EventArgs());
                    }
                    SendToTcpServer("Message", "", "没有打开串口,测量任务已终止!");
                    this.IsWorking = false;
                    return;
                }
                ResultData[] data = new ResultData[tempConfigPoints.Count];
                List<int> UnSuccessIdList = new List<int>();//补测id列表
                Thread.Sleep(1000);
                for (int i = 0; i < tempConfigPoints.Count; i++)
                {
                    
                    var ptName = 1;
                    try
                    {
                        ptName = Convert.ToInt32(tempConfigPoints[i].name);
                    }
                    catch
                    {
                        ptName = 1;
                    }
                    SendToTcpServer("Message", "", "观测" + ptName + "号点:");
                    Thread.Sleep(100);
                    MeasureDistanceData d = geo.Measure(ptName);
                    if (d.Distance != 0)
                    {
                        data[i] = new ResultData()
                        {
                            Slope = d.Distance,
                            Time = d.Time,
                            Point = new PointData() { E = d.Distance, N = d.Distance, H = d.Distance, Name = d.Id.ToString() }
                        };
                    }
                    else
                    {
                        UnSuccessIdList.Add(ptName);
                    }
                    string result = string.Format("距离:{0}m", d.Distance);
                    SendToTcpServer("Message", "", result);

                }
                //补测法则
                if (UnSuccessIdList.Count > 0)
                {
                    SendToTcpServer("Message", "", "开始补测");
                    Thread.Sleep(1000);
                    for (int k = 0; k < UnSuccessIdList.Count; k++)
                    {
                        int unSuccessId = UnSuccessIdList[k];
                        SendToTcpServer("Message", "", "观测" + unSuccessId.ToString() + "号点:");
                        Thread.Sleep(100);
                        MeasureDistanceData d = geo.Measure(unSuccessId);
                        var unSuccessIdindex = 0;
                        try
                        {
                            unSuccessIdindex = this.tempConfigPoints.FindIndex(p => p.name == unSuccessId.ToString());
                        }
                        catch
                        {
                            unSuccessIdindex = 0;
                        }
                        data[unSuccessIdindex] = new ResultData()
                        {
                            Slope = d.Distance,
                            Time = d.Time,
                            Point = new PointData() { E = d.Distance, N = d.Distance, H = d.Distance, Name = d.Id.ToString() }
                        };
                        string result = string.Format("距离:{0}m", d.Distance);
                        SendToTcpServer("Message", "", result);
                    }
                }
                Thread.Sleep(1000);
                SendToTcpServer("Message", "", "测量完成,等待仪器传输测量结果..........");
                try
                {
                    curTimeNo = datatrans.GetCurNo;
                    datatrans.SavePointsInRemoteDataBase(data, curTimeNo);
                }
                catch
                {
                    SendToTcpServer("Message", "", "远程数据库传输出现问题,测量完成但数据未上传!");
                    if (OnerrHappen != null)
                    {
                        para.result = "远程传输出现问题,测量完成但数据未上传!";
                        OnerrHappen(para, new EventArgs());
                    }
                    return;
                }
                if (OnSurveyComplete != null && para.Sender.Length > 0)
                {
                    para.result = "测量完成!";
                    OnSurveyComplete(para, new EventArgs());
                }
                SendToTcpServer("Command", "SurveyComplete", "");
                return;
            }
            catch (Exception a)
            {
                if (a.GetType() == typeof(ThreadAbortException))
                {
                    if (OnSurveyComplete != null)
                    {
                        para.result = "测量已成功被终止!";
                        OnSurveyComplete(para, new EventArgs());

                    }

                    return;
                }
                ToolClass.Log(a.Message);
                if (OnerrHappen != null)
                {
                    para.result = a.Message;
                    OnerrHappen(para, new EventArgs());
                }
                return;
            }
        }

        protected override void AutomaticSurvey()
        {

            this.IsWorking = true;
            //从config里找到所有的观测点
            this.tempConfigPoints = this.configPoints;
            Survey();
            this.IsWorking = false;
        }

        protected override void ManualSurvey()
        {
            ToolClass.Log(string.Format("ManualSurvey!!"));
            this.IsWorking = true;
            Survey();
            this.IsWorking = false;
        }


        //#######################接受远程命令
        public override void MsgCome(SendData data)
        {
            var cmd = data.Data.Command;
            switch (cmd)
            {
                case "GetAllPoints":
                    {
                        List<string> array = new List<string>();
                        for (int i = 0; i < this.configPoints.Count; i++)
                        {
                            array.Add(this.configPoints[i].name);
                        }
                        SendToTcpServer("Command", "GetAllPoints", array.ToArray());
                        break;
                    }
                case "StartSurvey":
                    {
                        if (this.IsWorking == false)
                        {
                            SendToTcpServer("Message", "", "测量指令已下达,等待仪器执行........");
                            try
                            {
                                JContainer ct = data.Data.Para as JContainer;
                                this.tempConfigPoints = new List<svpoint>();
                                foreach (var value in ct.AsJEnumerable())
                                {
                                    var strName = JsonConvert.DeserializeObject(value.ToString()).ToString();
                                    var pt = this.configPoints.SingleOrDefault(p => p.name == strName);
                                    this.tempConfigPoints.Add(pt);
                                }
                                if (this.tempConfigPoints.Count == 0)
                                {
                                    this.tempConfigPoints = this.configPoints;
                                }
                            }
                            catch
                            {
                                this.tempConfigPoints = this.configPoints;
                            }
                            this.StartSurvey(new CommandPara("", ""));
                        }
                        else
                        {
                            SendToTcpServer("Message", "", "正在执行测量任务");
                        }
                        break;
                    }
                case "StopSurvey":
                    {
                        this.StopSurvey();
                        SendToTcpServer("Message", "", "停止指令已下达,等待仪器执行.........");
                        break;
                    }
                default:
                    break;
            }

        }


    }
}
